package com.zx.mes.upms.hyl.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.mes.hyl.controller.BaseMethod;
import com.zx.mes.hyl.pagemodel.PageParam;
import com.zx.mes.hyl.response.ObjectRestResponse;
import com.zx.mes.hyl.response.TableResultResponse;
import com.zx.mes.upms.hyl.entity.*;
import com.zx.mes.upms.hyl.pagemodel.RolePage;
import com.zx.mes.upms.hyl.pagemodel.TreeNode;
import com.zx.mes.upms.hyl.service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/sysRole")
public class SysRoleController extends BaseMethod<SysRoleService, SysRole> {

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysServiceService sysServiceService;

    @Autowired
    private SysServicePermissionService sysServicePermissionService;

    /**
     * 使用要求:所有的表都必需有唯一key值,且名称为 REFLECTION_FIELD_NAME (id)
     *
     * @param entity 实体类(pojo)
     * @return ObjectRestResponse
     */
    @PreAuthorize("hasAuthority('back:role:save')")
    @ApiOperation(value = "添加一笔数据", notes = "根据id自生成(数据库),还是前端生成(自身成36位)")
    @PostMapping(value = "/add")
    public ObjectRestResponse<SysRole> save(@RequestBody SysRole entity) {
        entity.setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now());
        return super.add(entity);
    }

    @PreAuthorize("hasAuthority('back:role:query')")
    @ApiOperation(value = "根据所传id(数据库表的主键必需是id才能用)")
    @GetMapping(value = "getOne/{id}")
    public ObjectRestResponse<SysRole> getById(@ApiParam("id 是数据库的唯一主键") @PathVariable String id) {
        return super.get(id);
    }

    /**
     * @param entity 对应实体类
     * @return ObjectRestResponse
     */
    @PreAuthorize("hasAuthority('back:role:update')")
    @ApiOperation(value = "单笔更新操作", notes = "必需根据id来更新")
    @PutMapping(value = "update")
    public ObjectRestResponse<SysRole> updateByEntity(@RequestBody SysRole entity) {
        entity.setUpdateTime(LocalDateTime.now());
        return super.update(entity);
    }

    @PreAuthorize("hasAuthority('back:role:delete')")
    @ApiOperation(value = "单笔删除操作", notes = "必需根据id来删除")
    @DeleteMapping(value = "delete/{id}")
    public ObjectRestResponse<SysRole> del(@PathVariable String id) {
        return super.remove(id);
    }

    @PreAuthorize("hasAuthority('back:role:query')")
    @ApiOperation(value = "获取所有的数据", notes = "一般不推荐使用,小数据量可以")
    @GetMapping(value = "/all")
    public List<SysRole> getAll() {
        return super.all();
    }

    @PreAuthorize("hasAuthority('back:role:query')")
    @ApiOperation(value = "分页操作", notes = "params HashMap example = \"page=1&limit=5\"")
    @SuppressWarnings({"unchecked"})
    @GetMapping(value = "/page")
    public TableResultResponse page(@RequestParam Map<String, Object> params, SysRole entity) {
        TableResultResponse.Builder<SysRole> builder = new TableResultResponse.Builder();
        PageParam extPageParams = this.baseControllerExt.getPageParams(params);
        LambdaQueryWrapper<SysRole> lambda = new QueryWrapper<SysRole>().lambda();
        if (entity != null && StringUtils.isNotBlank(entity.getCode())) {
            lambda.like(SysRole::getCode, entity.getCode());
        }

        if (entity != null && StringUtils.isNotBlank(entity.getName())) {
            lambda.like(SysRole::getName, entity.getName());
        }

        List<SysRole> list = this.biz.page(new Page((long)extPageParams.getPage(), (long)extPageParams.getLimit()), lambda).getRecords();
        if (null != list && list.size() != 0) {
            builder.message("分页查询结果").total((long)list.size()).total((long)this.biz.count(null)).page((long)extPageParams.getPage()).rows(list);
        } else {
            builder.message("无数据").page(0L).rows(null);
        }

        return builder.build();
    }

    @PreAuthorize("hasAuthority('back:role:delete')")
    @DeleteMapping("/deleteBatch")
    public ObjectRestResponse<SysRole> deleteBatch(String ids) {
        ObjectRestResponse.Builder<SysRole> response = new ObjectRestResponse.Builder<>();
        /// 删除角色时,要处理 1.角色-用户中间表, 2.角色-权限表

        /// 参数检查
        if (StringUtils.isNotBlank(ids)) {
            List<String> list = this.baseControllerExt.divideStrToList(ids);
            if (list != null && list.size() > 0) {
                /// 1.删除 角色-用户中间表中的数据
                this.sysRoleUserService.remove(new QueryWrapper<SysRoleUser>().lambda().in(SysRoleUser::getRoleId, list));
                /// 2.删除 角色-权限中间表中的数据
                this.sysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().lambda().in(SysRolePermission::getRoleId, list));
                /// 3.删除 角色表中的数据
                this.biz.removeByIds(list);
                response.message("批量删除成功!");
            }else{
                response.message("没有可删除的数据!");
            }
        } else{
            response.message("所传参数无效,请检查!");
        }
        return response.build();
    }

    /**
     * 给角色授权
     *
     * @param sysRole        角色
     * @return response
     */
    @PostMapping("/grantPermission")
    public ObjectRestResponse<SysRole> grantPermission(@RequestBody SysRole sysRole) {
        ObjectRestResponse.Builder<SysRole> response = new ObjectRestResponse.Builder<>();
        /// 先删除中间表的内容 1.角色-权限中间表

        /// 1.删除 角色-权限中间表
        /// 参数检查
        if (StringUtils.isNotBlank(sysRole.getRoleId()) && StringUtils.isNotBlank(sysRole.getPermissionIds())) {
            this.sysRolePermissionService.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, sysRole.getRoleId()));
            /// 2.组合后向 角色-权限中间表插入
            List<String> list = this.baseControllerExt.divideStrToList(sysRole.getPermissionIds());
            List<SysRolePermission> sysRolePermissionList = new ArrayList<>(128);
            list.forEach(item -> {
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setPermissionId(Integer.valueOf(item)).setRoleId(Integer.valueOf(sysRole.getRoleId()));
                sysRolePermissionList.add(sysRolePermission);
            });
            this.sysRolePermissionService.saveBatch(new ArrayList<>(sysRolePermissionList));
            response.message("权限授权成功!");
        }else{
            response.message("传参无效,请检查所传参数!");
        }
        return response.build();
    }

    /**
     * 根据角色id获取对应的权限id
     * @param roleId 角色 id
     * @return RolePage
     */
    @GetMapping("/getPermissionByRoleId")
    public ObjectRestResponse<RolePage> getPermissionByRoleId(String roleId){
        ObjectRestResponse.Builder<RolePage> response = new ObjectRestResponse.Builder<>();
        /// 1.从 角色-权限表中获取权限信息
        List<SysRolePermission> list = this.sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId));
        if (list != null && list.size() > 0) {
            /// 2.从 权限表中获取权限详细信息
            List<Integer> permissionIdList = new ArrayList<>(32);
            list.forEach(item -> permissionIdList.add(item.getPermissionId()));
            List<SysPermission> sysPermissionList = this.sysPermissionService.list(new QueryWrapper<SysPermission>().lambda().in(SysPermission::getId, permissionIdList));
            response.message("角色获取权限详细信息成功!").data(sysPermissionList);
        }else {
            response.message("角色未获取到权限的详细信息!");
        }
        return response.build();
    }

    /**
     * 数据量在几万笔,是可以这样sql处理,过大时,要考虑是否加一些条件进行过滤
     * @return response
     */
    @GetMapping("/getAllPermissionByService")
    public ObjectRestResponse<TreeNode> getAllPermissionByService(){
        ObjectRestResponse.Builder<TreeNode> response = new ObjectRestResponse.Builder<>();
        /// 从数据库里表数据行数少的 服务 表中先获取数据
        List<SysService> sysServiceList = this.sysServiceService.list(new QueryWrapper<>());
        List<SysServicePermission> sysServicePermissionList = this.sysServicePermissionService.list(new QueryWrapper<>());
        List<SysPermission> sysPermissions = this.sysPermissionService.list(new QueryWrapper<>());
        List<TreeNode> treeNodeList = new ArrayList<>(256);
        if (sysServicePermissionList != null && sysServicePermissionList.size() > 0 && sysServiceList !=null && sysServiceList.size()>0) {
            sysServiceList.forEach(sysService -> {
                /// 第一级菜单
                TreeNode treeNode = new TreeNode();
                treeNode.setId(String.valueOf(sysService.getCode()+":"+sysService.getId())).setLabel(sysService.getCode());
                sysServicePermissionList.forEach((sysServicePermission -> {
                    if (sysService.getId().equals(sysServicePermission.getServiceId())) {
                        sysPermissions.forEach(sysPermission -> {
                            if (sysServicePermission.getPermissionId().equals(sysPermission.getId())) {
                                /// 第二级菜单
                                TreeNode node = new TreeNode();
                                node.setId(String.valueOf(sysPermission.getId())).setLabel(sysPermission.getPermission());
                                treeNode.getChildren().add(node);
                            }
                        });
                    }
                }));
                treeNodeList.add(treeNode);
            });
            response.message("权限获取成功!").data(treeNodeList);
        }else {
            response.message("未获取到权限相关信息!");
        }

        return response.build();
    }

}

